from common.models import Region, Site
from django.db.models import Model
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from book.models import Book, BookAuthor, Author, BookSource, BookDownloadUrl, AuthorType, Tag, Chapter, ChapterBody
from common.dao import get_site, get_default_region
from common.util import try_set_attrs, try_set_attr

from book.dao import save_book

def save_chapters(book_vm,book):
    for chapter_vm in book_vm.chapters:
        if chapter_vm.href == '#':
            chapter =_save_chapter(book,chapter_vm)
            for child_vm in chapter_vm.children:
                _save_chapter(book,child_vm,chapter)


def save_books(site, books):
    site = get_site(site[0], site[1])
    for book_vm in books:
        book = save_book(site, book_vm)
        save_chapters(book_vm,book)



def _save_chapter(book, chapter_vm, parent=None):
    try:
        chapter = Chapter.objects.get(title=chapter_vm.title, parent = parent, book = book, sort_no = chapter_vm.sort_no)    
    except ObjectDoesNotExist:
        chapter = Chapter(book=book,title = chapter_vm.title, parent= parent, sort_no = chapter_vm.sort_no,)       
    
    chapter.save()

    try:
        content = ChapterBody.objects.get(chapter=chapter)
    except ObjectDoesNotExist:
        try_set_attr(chapter_vm,'content','')
        content = ChapterBody(chapter = chapter,content = chapter_vm.content)
    content.save()
    return chapter
